import axios, { type AxiosRequestConfig, type AxiosRequestHeaders, type AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import pinia from "@/stores/index";
import { useUserInfoStore } from "../stores/userInfo";

/* 定义response对象的data接口 */
interface ResponseData<T> {
	succcess: boolean,
	code: number;
	data: T;
	message: string;
}

// 配置新建一个 axios 实例
const instance = axios.create({
	baseURL: import.meta.env.VITE_API_URL,
	timeout: 50000,
});

// 添加请求拦截器
instance.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		const userInfoStore = useUserInfoStore(pinia);
		if (userInfoStore.token) {
			// 请求头携带 token
			(config.headers as AxiosRequestHeaders).token = userInfoStore.token;
		}
		return config;
	});

// 添加响应拦截器
instance.interceptors.response.use(
	/* 约束一下response */
	async (response: AxiosResponse) => {
		// 对响应数据做点什么，简化服务器响应的数据
		const res = response.data;
		if (res.code !== 20000 && res.code !== 200) {
			/* 成功数据的code值为20000/200 */
			// 统一的错误提示
			ElMessage({
				message:
					(typeof res.data == "string" && res.data) || res.message || "Error",
				type: "error",
				duration: 5 * 1000,
			});

			// `token` 过期或者账号已在别处登录
			if (response.status === 401) {
				// 获取用户相关小仓库
				const storeUserInfo = useUserInfoStore(pinia);
				// 清空数据
				await storeUserInfo.reset();
				window.location.href = "/"; // 去登录页
				ElMessageBox.alert("你已被退出，请重新登录", "提示", {})
					.then(() => { })
					.catch(() => { });
			}
			return Promise.reject(instance.interceptors.response);
		} else {
			return res;
		}
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf("timeout") != -1) {
			ElMessage.error("网络超时");
		} else if (error.message == "Network Error") {
			ElMessage.error("网络连接错误");
		} else {
			if (error.response.data) ElMessage.error(error.response.statusText);
			else ElMessage.error("接口路径找不到");
		}
		return Promise.reject(error);
	}
);

// 封装GET请求
export const get = <T>(url: string, params?: object): Promise<ResponseData<T>> => {
  return instance.get<any, ResponseData<T>>(url, { params });
};

// // 封装POST请求
// export const post = <T>(url: string, data?: object): Promise<T> => {
//   return instance.post<T>(url, data);
// };

// // 封装PUT请求
// export const put = <T>(url: string, data?: object): Promise<T> => {
//   return instance.put<T>(url, data);
// };

// // 封装DELETE请求
// export const del = <T>(url: string): Promise<T> => {
//   return instance.delete<T>(url);
// };

export default instance;